import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {
    public static void processXml(File fIle, List<BilibiliUser> users, Map<String, Integer> userMap, String regex) throws DocumentException {
        //1.创建Reader对象
        SAXReader reader = new SAXReader();
        //2.加载xml
        Document document = reader.read(fIle);
        //3.获取根节点
        Element rootElement = document.getRootElement();
        Iterator iterator = rootElement.elementIterator();
        while (iterator.hasNext()){
            Element barrage = (Element) iterator.next();
            if(!barrage.getQName().getName().equals("d"))
                continue;
            List<Attribute> attributes = barrage.attributes();
            // 获取弹幕内容以及id
            String raw = barrage.content().get(0).toString();
            String content = getContent(raw);
            String name = attributes.get(1).getValue();
            // 判断此人是否违反弹幕礼仪
            if(Pattern.matches(regex, content)) {
                // 判断此人是否已经存在
                int pos;
                if(userMap.containsKey(name)) {
                    pos = userMap.get(name);
                } else { // 添加此人
                    pos = users.size();
                    userMap.put(name, pos);
                    users.add(new BilibiliUser(name, 0 , new ArrayList<>()));
                }

                users.get(pos).barrageNum++;
                users.get(pos).barrage.add(content);
            }
        }
        return;
    }

    public static String getContent(String raw) {
        Pattern regex1 =Pattern.compile("\\[Text: \\\"");
        Pattern regex2 =Pattern.compile("\\\"\\]");
        Matcher mt1 = regex1.matcher(raw);
        Matcher mt2 = regex2.matcher(raw);

        int st = 0;
        int ed = 0;

        while(mt1.find()) {
            st = mt1.start() + 8;
        }
        while(mt2.find()) {
            ed = mt2.start();
        }
        String ans = raw.substring(st, ed);
        return ans;
    }
}
